﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Threading;
using System.Globalization;
using Nivdal.AuxCode;
using System.Web.Script.Services;

namespace Nivdal
{
    public partial class MasterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            string UserId = ou.UserId;
            this.HiddenUserId.Value = UserId;
            
            // url redirection
            if (!IsPostBack)
            {
                string Url = Request.Url.ToString();
                if (!Url.Contains("www") && !(Url.Contains("localhost")) && !(Url.Contains("int.")) && !(Url.Contains("int2.")))
                {
                    string newurl = Url.Replace("http://", "http://www.");
                    //MessageLabel.Text = "will be redirected to: <br /> " + newurl;
                    Response.Redirect(newurl);
                }
                //AddsPanel.Visible = (!ou.IsPremium);
                //Image1.Visible = (ou.IsPremium);
                /// adds are not yet in the site
                AddsPanel.Visible = false;                
            }
            // for user that is not approved yet - seek for approval and redirect him to registration message page if he was approved
            if ((ou.ApprovalStatus == "1") || (ou.ApprovalStatus == "4"))
            {
                string status = GND.ReadNivdalIntData("@UserId", "Nivdal_GetUserApprovalStatus", ou.UserId);
                if (status != "1" && status != "4")
                {
                    Response.Redirect("~/RegistrationMessage.aspx");
                }
            }

            FriendsUpdatesPanel.Visible = ou.IsPremium;

            // deal with Newbie tooltips
            if ((!IsPostBack) && (ou.UserId != null))
            {
                // showing newbie tip
                ShowNewbieTip();
                
                // the text was shown. Now - if the stage is temporary one time stage - move it to the next one.
                if ((int)Session["NewbieTipStage"] == 2)
                {
                    Session["NewbieTipStage"] = 3;
                    Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", "3", ou.Language);
                    GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, "3");
                }
                else if ((int)Session["NewbieTipStage"] == 4)
                {
                    Session["NewbieTipStage"] = 5;
                    Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", "5", ou.Language);
                    GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, "5");
                }
                else if ((int)Session["NewbieTipStage"] == 6)
                {
                    Session["NewbieTipStage"] = 7;
                    Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", "7", ou.Language);
                    GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, "7");
                }
                else if ((int)Session["NewbieTipStage"] == 8)
                {
                    Session["NewbieTipStage"] = 9;
                    Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", "9", ou.Language);
                    GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, "9");
                }
                else if ((int)Session["NewbieTipStage"] == 10)
                {
                    Session["NewbieTipStage"] = 99;
                    Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", "99", ou.Language);
                    GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, "99");
                }
                else if ((int)Session["NewbieTipStage"] == 99)
                {
                    Session["NewbieTipStage"] = 100;
                    Session["NewbieTipText"] = "";
                    GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, "100");
                }

            }
            else if (ou.UserId == null)
                NewbieTipsPanel.Visible = false;

            
            //MenuContentPlaceholder_FriendsOnlineListView
            //UpdatePanel up = (Master.FindControl("FriendsOnlineUpdatePanel") as UpdatePanel);
            //ImageButton UserImage = (ImageButton)FriendsOnlineListView.Items[0].FindControl("UserImage");
            //UserImage.Attributes.Add("OnKeyPress", "return disableEnterKey(event);");

            //Button delete = (Button)rptNotering.Items[0].FindControl("btnDelete");
            //Repeater rp = (Repeater)up.FindControl("FriendsOnlineListView") as Repeater;

            //ContentPlaceHolder cph = (ContentPlaceHolder)Page.Master.Controls[0].FindControl("ContentPlaceHolder2");
            //UpdatePanel up = (UpdatePanel)cph.FindControl("FriendsOnlineUpdatePanel");
            //ImageButton UserImage = (ImageButton)rp.FindControl("UserImage");
            //UserImage.Attributes.Add("OnKeyPress", "return disableEnterKey(event);");
            
            //if (!HttpContext.Current.User.Identity.IsAuthenticated)
            //    Response.Redirect("~/Default.aspx");
          
            
            if (!IsPostBack)
            {
                //string UserId = GND.ReturnUserId();
                this.FriendsStatusChangesDataSource.SelectParameters.Add("UserId", ou.UserId);
                this.FriendsStatusChangesDataSource.SelectParameters.Add("Type", "0");
                ShowNumSuggestionsPanel();
                     
            }
            if (Request.UserAgent.IndexOf("AppleWebKit") > 0)
            {
                Request.Browser.Adapters.Clear();
            }

        }
        protected void Page_PreInit(object sender, EventArgs e)
        {
            // This is necessary because Safari and Chrome browsers don't display the Menu control correctly.
            // All webpages displaying an ASP.NET menu control must inherit this class.
            if (Request.ServerVariables["http_user_agent"].IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) != -1)
                Page.ClientTarget = "uplevel";
        }
        
        protected void Page_PreRender(Object sender, EventArgs e)
        {
            //GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                //string UsrId = ou.UserId;
                //string UserAccessLevel = ou.UserAccessLevel;
                //string TeamId = ou.TeamId;
                //UserAccessLevel = (GND.ReadNivdalIntData("@UserId", "Nivdal_GetUserLevel", UsrId));
                //TeamId = (GND.ReadNivdalIntData("@UserId", "Nivdal_GetTeamIdByUserId", UsrId));

                if (!ou.IsPremium)
                {
                    //Menu8.Visible = false;
                    Menu8.Items[0].ChildItems[1].Enabled = false;
                    //Menu8.Items[0].ChildItems[2].Enabled = false; - friends page will be still visible. 
                    Menu8.Items[0].ChildItems[3].Enabled = false;
                }

                if (!ou.PremiumEnabled)
                {
                    Menu8.Items[0].ChildItems[0].Enabled = false;
                    Menu8.Items[0].ChildItems[4].Enabled = false;
                }


                if (ou.UserAccessLevel == "1")
                {
                    Menu6.Visible = false;
                }

                if (ou.UserAccessLevel != "5")
                {
                    Menu9.Visible = false;
                }
                else
                {
                    Menu6.CssClass = "floater menu_static menu_static_border";
                }

                //In case the user does not have a team yet
                if ((ou.UserAccessLevel == ("0")) || ou.TeamId == null)
                {
                    this.Menu2.Visible = false;
                    this.Menu3.Visible = false;
                    this.Menu4.Visible = false;
                    this.Menu5.Visible = true;
                    this.Menu5.CssClass = "floater menu_static";
                    this.Menu6.Visible = false;
                    this.Menu7.Visible = false;
                    this.Menu8.Visible = false;
                    this.Menu9.Visible = false;
                    this.PlayersMenu.Visible = false;
                }
                else 
                {
                    // Setting country name
                    Menu3.Items[0].ChildItems[0].Text = ou.CountryName;
                    Menu3.Items[0].Text = ou.CountryName;

                    //showing national teams in the menu
                    if (ou.NationalTeamId != "0")
                    {
                        MenuItem nt = new MenuItem();
                        nt.Text = ou.NationalTeamName;
                        nt.Value = ou.NationalTeamName;
                        nt.NavigateUrl = "~/NationalTeam.aspx?Id=" + ou.NationalTeamId;
                        Menu3.Items[0].ChildItems.Add(nt);
                    }
                    if (ou.U19TeamId != "0")
                    {
                        MenuItem ntu = new MenuItem();
                        ntu.Text = ou.U19TeamName;
                        ntu.Value = ou.U19TeamName;
                        ntu.NavigateUrl = "~/NationalTeam.aspx?Id=" + ou.U19TeamId;
                        Menu3.Items[0].ChildItems.Add(ntu);
                    }
                }

                // if user is admin is some way Admin menu will be visible
                if ((ou.UserAccessLevel == ("2") || (ou.UserAccessLevel == ("3")) || (ou.UserAccessLevel == ("4")) || (ou.UserAccessLevel == ("5"))))
                {
                    this.Menu6.Visible = true;
                    this.Menu8.CssClass = "floater menu_static menu_static_border";
                }
                else
                {
                    this.Menu6.Visible = false;
                }

                // Add news, Admin Approve users, and sponsors summary is for admins only
                // this.Menu6.Items[0].ChildItems[0] - AddNews
                this.Menu6.Items[0].ChildItems[1].Enabled = (ou.UserAccessLevel == "5");

                // this.Menu6.Items[0].ChildItems[1] - ApproveUsers
                this.Menu6.Items[0].ChildItems[2].Enabled = ((ou.UserAccessLevel == "4") || (ou.UserAccessLevel == "5"));

                // this.Menu6.Items[0].ChildItems[2] - Translate
                //this.Menu6.Items[0].ChildItems[3].Enabled = ((ou.UserAccessLevel == "3") || (ou.UserAccessLevel == "5"));
                this.Menu6.Items[0].ChildItems[3].Enabled = (ou.TranslatesTo != "0");

                // this.Menu6.Items[0].ChildItems[3] - ManageForumPunishments
                this.Menu6.Items[0].ChildItems[4].Enabled = ((ou.UserAccessLevel == "2") || (ou.UserAccessLevel == "4") || (ou.UserAccessLevel == "5"));
                
                this.NTMenu.Visible = (ou.NationalTeamCoach != "0");

                //if (UserAccessLevel == ("5"))
                //{
                //    this.Menu6.Items[0].ChildItems[0].Enabled = true;
                //    this.Menu6.Items[0].ChildItems[2].Enabled = true;
                //    this.Menu6.Items[0].ChildItems[5].Enabled = true;
                //    this.Menu6.Items[0].ChildItems[6].Enabled = true;
                //    this.Menu6.Items[0].ChildItems[7].Enabled = true;
                //    this.Menu6.Items[0].ChildItems[8].Enabled = true;
                //}
                //else
                //{
                //    this.Menu6.Items[0].ChildItems[0].Enabled = false;
                //    this.Menu6.Items[0].ChildItems[2].Enabled = false;
                //    this.Menu6.Items[0].ChildItems[5].Enabled = false;
                //    this.Menu6.Items[0].ChildItems[6].Enabled = false;
                //}

                //// Translation is for translators and Admins
                //if ((UserAccessLevel == ("2")) || (UserAccessLevel == ("5")))
                //{
                //    this.Menu6.Items[0].ChildItems[3].Enabled = true;
                //}
                //else
                //{
                //    this.Menu6.Items[0].ChildItems[3].Enabled = false;
                //}

                //// Approve users for GMs and adminsw
                //if ((UserAccessLevel == ("4")) || (UserAccessLevel == ("5")))
                //{
                //    this.Menu6.Items[0].ChildItems[1].Enabled = true;
                //}
                //else
                //{
                //    this.Menu6.Items[0].ChildItems[1].Enabled = false;
                //}

                //// Forum punishments Mods, GMs and Admins.
                //if ((UserAccessLevel == ("3") || (UserAccessLevel == ("4")) || (UserAccessLevel == ("5"))))
                //{
                //    this.Menu6.Items[0].ChildItems[5].Enabled = true;
                //}
                //else
                //{
                //    this.Menu6.Items[0].ChildItems[5].Enabled = false;
                //}

                // log user login.
                string IP = GetIP();
                SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                SqlCommand cmd = new SqlCommand("Nivdal_LogUserActivity", conn);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@UserId", ou.UserId);
                cmd.Parameters.AddWithValue("@IP", IP);

                //cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier);
                //cmd.Parameters["@UserId"].Direction = ParameterDirection.Input;
                //cmd.Parameters["@UserId"].Value = UsrId;

                //cmd.Parameters.Add("@IP", SqlDbType.NVarChar, 46);
                //cmd.Parameters["@IP"].Direction = ParameterDirection.Input;
                //cmd.Parameters["@IP"].Value = IP;

                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                    Response.Redirect("~/Default.aspx");
                }
                finally
                {
                    conn.Close();
                }

                //ContentDirection dir = (Master.FindControl("DirectionPanel") as Panel).Direction;
                //if (dir == ContentDirection.LeftToRight)
                //{
                //    this.MasterLinksPanel.Direction = ContentDirection.RightToLeft;
                //}
                //else
                //{
                //    this.MasterLinksPanel.Direction = ContentDirection.LeftToRight;
                //}

               

            }
            else
            {
                this.Menu2.Visible = false;
                PlayersMenu.Visible = false;
                this.Menu3.Visible = false;
                this.Menu4.Visible = true;
                this.Menu4.CssClass = "floater menu_static menu_static_border_first";
                this.Menu4.Items[0].ChildItems[2].Enabled = false;
                this.Menu4.Items[0].ChildItems[3].Enabled = false;
                this.Menu5.Visible = true;
                this.Menu7.Visible = true;
                this.Menu7.CssClass = "floater menu_static menu_static_border_last";
                Menu7.Items[0].ChildItems[1].Enabled = false;
                this.Menu6.Visible = false;
                this.Menu8.Visible = false;
                this.Menu9.Visible = false;                
                this.NTMenu.Visible = false;
            }

        }

        public string GetIP()
        {
            try
            {
                HttpRequest currentRequest = HttpContext.Current.Request;
                string ipAddress = currentRequest.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (ipAddress == null || ipAddress.ToLower() == "unknown")
                    ipAddress = currentRequest.ServerVariables["REMOTE_ADDR"];

                return ipAddress;
            }
            catch (Exception ex)
            {
                return ex.ToString(); 
            }
        }

        

        protected void FriendsOnlineListView_OnItemCreated(object source, RepeaterItemEventArgs e)
        {
            ImageButton UserImage = (ImageButton)e.Item.FindControl("UserImage");
            UserImage.Attributes.Add("OnKeyPress", "return disableEnterKey(event);");

        }

        protected void ToggleTipsDetails(object sender, EventArgs e)
        {
            if ((bool)Session["NewbieTipDetailsVisible"] == true)
            {
                // hide details
                TipDetailsPanel.Visible = false;
                //ShowTipDetailsPanel.Visible = true;
                ShowHideTipsImage.ImageUrl = "~/Images/Icons/TeamHomePageIcons/show_det.png";
                Session["NewbieTipDetailsVisible"] = false;

            }
            else
            { 
                // show details
                TipDetailsPanel.Visible = true;
                //ShowTipDetailsPanel.Visible = false;
                ShowHideTipsImage.ImageUrl = "~/Images/Icons/TeamHomePageIcons/hide_det.png";
                Session["NewbieTipDetailsVisible"] = true;
            }
            ShowNewbieTip();

        }

        protected void MoveToPreviousTip(object sender, EventArgs e)
        {
            // a trick - taking the tip stage not from the session, but from the displayed label.
            // this is in order not to jump over one tip on pages that change the tips by themselves

            int Tipstage;
            if (!int.TryParse(TipNumberLabel.Text.Substring(0, 1), out Tipstage))
                Tipstage = (int)Session["NewbieTipStage"];
            else
            {
                if (Tipstage == int.Parse(GetNivdalData.GetNivdalData.TotalNewbieTips))
                {
                    Tipstage = 99;
                }
                else    
                    Tipstage = Tipstage * 2 - 1;
            }

            if ((Tipstage == 100) || (Tipstage == 99))
                Tipstage = 9;
            else if ((Tipstage == 9) || (Tipstage == 10))
                Tipstage = 7;
            else if ((Tipstage == 7) || (Tipstage == 8))
                Tipstage = 5;
            else if ((Tipstage == 5) || (Tipstage == 6))
                Tipstage = 3;
            else if ((Tipstage == 3) || (Tipstage == 4))
                Tipstage = 1;

            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            Session["NewbieTipStage"] = Tipstage;
            Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", Tipstage.ToString(), ou.Language);
            GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, Tipstage.ToString());

            ShowNewbieTip();
        }

        protected void MoveToNextTip(object sender, EventArgs e)
        {
            // a trick - taking the tip stage not from the session, but from the displayed label.
            // this is in order not to jump over one tip on pages that change the tips by themselves

            int Tipstage;
            if (!int.TryParse(TipNumberLabel.Text.Substring(0, 1), out Tipstage))
                Tipstage = (int)Session["NewbieTipStage"];
            else
                Tipstage = Tipstage * 2 - 1;

            if ((Tipstage == 1) || (Tipstage == 2))
                Tipstage = 3;
            else if ((Tipstage == 3) || (Tipstage == 4))
                Tipstage = 5;
            else if ((Tipstage == 5) || (Tipstage == 6))
                Tipstage = 7;
            else if ((Tipstage == 7) || (Tipstage == 8))
                Tipstage = 9;
            else if ((Tipstage == 9) || (Tipstage == 10))
                Tipstage = 99;
            else
                Tipstage = 100;

            OnlineUser ou = (OnlineUser)Session["User"];
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

            Session["NewbieTipStage"] = Tipstage;
            Session["NewbieTipText"] = GND.ReadNivdalStringData("TipId", "Language", "dbo.Nivdal_NewbieTipsGetTip", Tipstage.ToString(), ou.Language);
            GND.ExecNivdalSQL("UserId", "StageId", "Nivdal_NewbieTipsSetStage", ou.UserId, Tipstage.ToString());

            ShowNewbieTip();
        }

        private void ShowNewbieTip()
        {
            int Stage = (int)Session["NewbieTipStage"];
            
            if (Stage == 100)
            {
                NewbieTipsPanel.Visible = false;
            }
            else
            {
                OnlineUser ou = (OnlineUser)Session["User"];
                GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();

                // position:
                string[] position = (GND.ReadNivdalStringData("UserId", "Nivdal_GetUserTopLeftTipsPosition", ou.UserId)).Split(',');
                TopHiddenField.Value = position[0];
                LeftHiddenField.Value = position[1];
                DirHiddenField.Value = ou.TextDir;
                
                if (ou.IsRTL())
                {
                    PrevTipLinkButton.ImageUrl = "~/Images/MatchInstructions/RightArrow.png";
                    NextTipLinkButton.ImageUrl = "~/Images/MatchInstructions/LeftArrow.png";
                }

                if ((bool)Session["NewbieTipDetailsVisible"] == false)
                {
                    TipDetailsPanel.Visible = false;
                    ShowHideDetailsLinkButton.Text = Resources.Resource.Friendly_ShowDetailsText;
                    ShowHideTipsImage.ImageUrl = "~/Images/Icons/TeamHomePageIcons/show_det.png";
                }
                else
                {
                    TipDetailsPanel.Visible = true;
                    ShowHideDetailsLinkButton.Text = Resources.Resource.Friendly_HideDetailsText;
                    ShowHideTipsImage.ImageUrl = "~/Images/Icons/TeamHomePageIcons/hide_det.png";

                    NewbieTipLabel.Text = (string)Session["NewbieTipText"];
                    TipNumberLabel.Text = GetNivdalData.GetNivdalData.GetTipNumber(Session["NewbieTipStage"]) + "/" +
                                          //Resources.Resource.Translate_StatusOutOfLabelText + " " +
                                          GetNivdalData.GetNivdalData.TotalNewbieTips;

                    if (Stage == 1)
                    {
                        PrevTipLinkButton.Visible = false;
                    }
                    else
                    {
                        PrevTipLinkButton.Visible = true;
                    }
                    if (Stage == 99)
                    {
                        NextTipLinkButton.Visible = false;
                    }
                    else
                    {
                        NextTipLinkButton.Visible = true;
                    }
                }

                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "showalert", "InitNewbieTips();", true);
            }

            

        }

        protected void FriendsStatusRefresh(object sender, EventArgs e)
        {
            
            
            StatusChangesRepeater.DataBind();
            ShowNumSuggestionsPanel();
            
        }

        private void ShowNumSuggestionsPanel()
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            OnlineUser ou = (OnlineUser)Session["User"];

            string NumSuggestions = GND.ReadNivdalIntData("UserId", "Nivdal_FriendsGetNumberOfFriendsSuggestions", ou.UserId);
            if (NumSuggestions != "0")
                NumSuggestionsLabel.Text = "(" + NumSuggestions + " " + Resources.Resource.Friends_SuggestionsTitleLabelText + ")";
            else
                NumSuggestionsPanel.Visible = false;
        }
        


        //protected void Page_PreInit(object sender, EventArgs e)   
        //{    
        //    if (Request.ServerVariables["http_user_agent"].IndexOf("Chrome", StringComparison.CurrentCultureIgnoreCase) != -1)   
        //        Page.ClientTarget = "uplevel";   
        //    if (Request.ServerVariables["http_user_agent"].IndexOf("Safari", StringComparison.CurrentCultureIgnoreCase) != -1)   
        //        Page.ClientTarget = "uplevel";   
        //}  

        //public AjaxControlToolkit.ValidatorCalloutPosition ValidatorPosition()
        //{
        //    //if ((Master.FindControl("DirectionPanel") as Panel).Direction == ContentDirection.RightToLeft)
        //    //    return AjaxControlToolkit.ValidatorCalloutPosition.TopRight;
        //    return AjaxControlToolkit.Va.TopLeft;
        //}

    }
}